<template>
  <div :class="[$style.container]" @keyup.enter="onSubmit">
    <div :class="[$style.title]">账号密码登录</div>
    <el-form :model="form" :rules="rules" ref="fm">
      <el-form-item prop="identifier" required>
        <el-input v-model.trim="form.identifier" placeholder="手机号、邮箱或账号"></el-input>
      </el-form-item>
      <el-form-item prop="credential" required>
        <el-input v-model.trim="form.credential" type="password" placeholder="密码">
          <template v-slot:suffix="">
            <span>
              <el-divider direction="vertical"></el-divider>
              <el-link :underline="false" :class="[$style.text]" @click="onForgetPassword">忘记密码?</el-link>
            </span>
          </template>
        </el-input>
      </el-form-item>
      <div class="mb-3">
        <el-checkbox v-model="keep">记住密码</el-checkbox>
      </div>
      <el-form-item>
        <el-button type="primary" style="width: 100%;" :loading="submitting" @click="onSubmit" >登录</el-button>
      </el-form-item>
      <div :class="[$style.extra]">
        <el-link :underline="false" style="font-size: 12px;" @click="onGoCode" v-if="allowPhone">短信验证码登录</el-link>
        <el-link :underline="false" style="font-size: 12px;"  @click="onGoRegistry" v-if="allowRegisterAccount">注册新账号</el-link>
      </div>
    </el-form>
    <el-divider></el-divider>
    <action-list></action-list>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Ref, Emit } from 'vue-property-decorator'
import ActionList from '../action-list/index.vue'
import { isAccountRegistered, isAccountBound, resetPhoneCredential, registerPhone, bindPhone } from '@/api/account'
import { phoneValidator } from '@/config/validator'
import { AppModule } from '@/store'
import { remote } from 'electron'

let isFirst = true

function getClLoginInfo () {
  if (!isFirst) return null
  const args = remote.process.argv
  const uf = '--username='
  const pf = '--password='
  const username = (args.find(v => v.startsWith(uf)) || '').replace(uf, '')
  const password = (args.find(v => v.startsWith(pf)) || '').replace(pf, '')
  if (!username || !password) return null
  isFirst = false
  return { username, password }
}

@Component({
  components: { ActionList }
})
export default class AccountLogin extends Vue {
  @Prop(String) type!: 'phone' | 'username'

  @Ref() fm!: any

  @Emit('update:type') updateType (type: 'phone' | 'username' | 'registry') {}

  @AppModule.State properties!: any

  clLoginInfo: any = getClLoginInfo()

  form = {
    identifier: (this.$storage.get('account', 'common') as any)?.identifier || '',
    credential: (this.$storage.get('account', 'common') as any)?.credential || '',
    type: 'username'
  }

  submitting = false

  localKeep = localStorage.getItem('keep') === '1'

  get keep () {
    return this.localKeep
  }

  set keep (value: boolean) {
    if (value) {
      localStorage.setItem('keep', '1')
      this.localKeep = true
    } else {
      localStorage.removeItem('keep')
      this.localKeep = false
    }
  }

  get rules () {
    return {
      identifier: [
        { required: true, message: '请输入账号' }
      ],
      credential: [
        { required: true, message: '请输入密码' }
      ]
    }
  }

  get allowRegisterAccount () {
    return !!this.properties?.deploy?.allowRegisterAccount
  }

  get allowPhone () {
    return !this.properties?.deploy?.disabledPhoneRegistry
  }

  onSubmit () {
    this.fm.validate((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      this.$auth.login(this.form as any).then(() => {
        if (this.keep) {
          this.$storage.set('account', this.form, 'common')
        } else {
          this.$storage.set('account', undefined, 'common')
        }
      }).catch(() => {
        this.$notify.warning('帐号或密码错误')
      }).finally(() => {
        this.submitting = false
      })
    })
  }

  onGoCode () {
    this.updateType('phone')
  }

  onGoRegistry () {
    this.updateType('registry')
  }

  onForgetPassword () {
    const identifier = this.form.identifier || undefined
    this.$router.push({ path: '/forgot-password', query: { identifier } })
  }

  mounted () {
    if (this.clLoginInfo && this.clLoginInfo?.username && this.clLoginInfo?.password) {
      this.form.identifier = this.clLoginInfo?.username
      this.form.credential = this.clLoginInfo?.password
      this.$nextTick(() => {
        this.onSubmit()
      })
    }
  }

  // $auth!: any
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.title {
  margin-bottom: 12px;
}

.text {
  font-size: 12px;
  margin-right: 8px;
  color: $text-secondary-color;
}

.extra {
  display: flex;
  justify-content: space-between;
}
</style>
